package com.google.code.jdbclogger.formatter;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @author Andrey Vityuk
 */
public class SqlJdbcFormatter {
    private static final char PLACEHOLDER = '?';

    private final String sql;
    private final List<Object> parameters;

    public SqlJdbcFormatter(final String sql) {
	if (sql == null) {
	    throw new NullPointerException("Parameter 'sql' must be not null.");
	}

	this.sql = sql;
	this.parameters = createList(countParameter(sql));
    }

    public void setParameter(final int index, final Object value) {
	if (index < 1 || index > parameters.size()) {
	    throw new IllegalArgumentException("Parameter 'index' must be in range 1 <= index <= n");
	}

	parameters.set(index - 1, value);
    }

    public String format() {
	StringBuilder qb = new StringBuilder(sql.length());

	String rest = sql;
	for (Object parameter : parameters) {
	    int paramPos = rest.indexOf(PLACEHOLDER);

	    qb.append(rest.substring(0, paramPos));
	    qb.append(parameter);

	    rest = rest.substring(paramPos + 1);
	}
	qb.append(rest);

	return qb.toString();
    }

    private static int countParameter(String sql) {
	int count = 0;
	for (int i = 0, n = sql.length(); i < n; i++) {
	    if (sql.charAt(i) == PLACEHOLDER) {
		count++;
	    }
	}

	return count;
    }

    private static List<Object> createList(int size) {
	if (size == 0) {
	    return Collections.emptyList();
	} else {
	    return Arrays.asList(new Object[size]);
	}
    }
}
